package com.gxa.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.R;
import com.gxa.entity.SysUser;
import com.gxa.mapper.SysUserMapper;
import com.gxa.service.SysUserService;
import com.gxa.utils.JwtUtils;
import com.gxa.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public R select(String username,String password, HttpServletResponse response) {
        R r = new R();
        try{
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
            subject.login(usernamePasswordToken);
            r.setCode(200);
            r.setMsg("登录成功！");
            //1.登录成功后，后端生成token令牌。
            String authorization =  JwtUtils.createJwt(UUID.randomUUID().toString(),JwtUtils.JWT_SECERT, JSONObject.toJSONString(usernamePasswordToken),JwtUtils.TTMILLIS);
            //2.通过响应头返回给前端
            response.setHeader("Authorization",authorization);
        }catch (UnknownAccountException e){
            System.out.println("==账户有误==");
            r.setCode(500);
            r.setMsg("账户或密码有误");
        }catch (IncorrectCredentialsException e){
            System.out.println("==密码有误==");
            r.setCode(500);
            r.setMsg("账户或密码有误");
        }catch (LockedAccountException e){
            System.out.println("==账号被锁==");
            r.setCode(500);
            r.setMsg("账号被锁");
        }catch (AuthenticationException e){
            System.out.println("==认证错误==");
            r.setCode(500);
            r.setMsg("认证错误");
        }
        return r;
    }

    @Override
    public R selectAll() {
        R r = new R();
        List<SysUser> sysUsers = sysUserMapper.selectAll();
         if (sysUsers!=null){
             r.setCode(200);
             r.setMsg("查询成功");
             r.setData(sysUsers);
         }
        return r;
    }
}
